<%@page import="org.apache.commons.lang3.StringUtils"%>
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="fi.foyt.cs.persistence.domainmodel.oauth.AuthorizedClient"%>
<%@page import="fi.foyt.cs.controller.OAuthController"%>
<%@page import="fi.foyt.cs.api.SystemProperty"%>
<%@page import="fi.foyt.cs.Settings"%>
<%
  String logout = request.getParameter("logout");
  String accessToken = request.getParameter("accessToken");

  if (StringUtils.isBlank(accessToken)) {
    OAuthController oAuthController = new OAuthController();  
    String htmlClientId = Settings.getValue(SystemProperty.HTML_CLIENT);
    AuthorizedClient authorizedClient = oAuthController.findAuthorizedClientByClientId(htmlClientId);

    String host = Settings.getValue(SystemProperty.HOST);
    String port = Settings.getValue(SystemProperty.PORT);
    
    String clientId = URLEncoder.encode(htmlClientId, "UTF-8");
    String clientSecret = URLEncoder.encode(authorizedClient.getClientSecret(), "UTF-8");
    String redirectUrl = URLEncoder.encode(authorizedClient.getReturnUrl(), "UTF-8");   
    String code = URLEncoder.encode(request.getParameter("code"), "UTF-8");
    
    String accessTokenUrl = "http://" + host + ':' + port + "/oauth/access_token";
    
    pageContext.setAttribute("accessTokenUrl", "/oauth/access_token_g?client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + code + "&grant_type=authorization_code&redirect_uri="+ redirectUrl);
  } else {
    String returnUrl = null;
    for (Cookie cookie : request.getCookies()) {
      if ("csOAuthReturnUrl".equals(cookie.getName()))
        returnUrl = cookie.getValue();
    }
    
    session.setAttribute("clientOAuth", accessToken);
    if (returnUrl != null) {
      Cookie returnCookie = new Cookie("csOAuthReturnUrl", "");
      returnCookie.setPath("/");
      returnCookie.setMaxAge(-1);
      response.addCookie(returnCookie);
      response.sendRedirect(returnUrl);
    }    
  }
%>

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Criminal Souls</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/script/prototype/prototype.js"></script>
<script type="text/javascript">
  document.observe("dom:loaded", function() {
    new Ajax.Request('${accessTokenUrl}', {
      method : 'GET',
      onSuccess : function(response) {
        window.location.href = window.location.pathname + '?accessToken=' + response.responseJSON['access_token'];
      },
      onFailure : function(response) {
        $(document.body).update('<p style="color: red">Error occured while retriving access token: ' + response.responseText + '</p>');
      }
    });
  });
</script>
</head>
<body>
  Please wait...
</body>
</html>